package com.yantong.service.impl;

import com.yantong.utils.PageUtils;
import com.yantong.pojo.Payment;
import com.yantong.pojo.PaymentListParams;
import com.yantong.mapper.PaymentMapper;
import com.yantong.service.PaymentService;
import com.yantong.pojo.Order;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author kanghaixin
 * @date 2018/9/18.14:13
 */
@Service
public class PaymentServiceImpl implements PaymentService {
    @Autowired
    private PaymentMapper paymentMapper;


    private static Logger logger = LoggerFactory.getLogger(PaymentServiceImpl.class);

    @Override
    public PageUtils<Payment> listPayments(PaymentListParams params, int offset, int limit) {
        PageUtils<Payment> pageUtils = new PageUtils<>();

        int total = paymentMapper.countByParams(params);
        if (total >0) {
            pageUtils.setTotal(total);
            pageUtils.setRows(paymentMapper.listByParams(params, new RowBounds(offset, limit)));
        }
        return pageUtils;
    }

    @Override
    public List<Payment> listPayments(PaymentListParams params) {
        return paymentMapper.listByParams(params);
    }

    @Override
    @Async
    public void savePayment(Order order) {
        if (order == null) {
            return;
        }
        logger.info("save payment,orderId:{},outTradeNo:{},payNo:{}", order.getId(), order.getOutTradeNo(), order.getPayno());
        Payment payment = new Payment();
        payment.setOutTradeNo(order.getOutTradeNo());
        payment.setPayTradeNo(order.getPayno());
        payment.setMoney(order.getPayprice());
        payment.setStatus(2);
        payment.setType(String.valueOf(order.getPaytype()));
        payment.setStyle(3);
        payment.setMid(order.getMid());
        payment.setOpenid(order.getOpenid());
        payment.setCreateTime(order.getCreateTime());
        payment.setUpdateTime(order.getPayTime());
        paymentMapper.insertSelective(payment);
    }

    @Override
    public int savePayment(Payment payment) {
        if (payment == null) {
            return 0;
        }
        return paymentMapper.insertSelective(payment);
    }
}
